package aliyun.cx.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aliyun.cx.admin.entity.Comment;
import aliyun.cx.admin.mapper.CommentMapper;
import aliyun.cx.admin.service.CommentService;
import aliyun.cx.admin.service.ArticleTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评论服务实现类
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    
    private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);
    
    @Autowired
    private ArticleTagService articleTagService;

    @Override
    public IPage<Comment> getCommentPageWithRelations(int page, int size, Long userId, Long articleId, Long parentId, Integer status, String content) {
        try {
            Page<Comment> pageParam = new Page<>(page, size);
            IPage<Comment> commentPage = baseMapper.selectCommentPageWithRelations(
                pageParam, userId, articleId, parentId, status, content
            );
            
            // 为每个评论添加文章标签信息
            commentPage.getRecords().forEach(comment -> {
                if (comment.getArticleId() != null) {
                    try {
                        comment.setArticleTags(articleTagService.getTagsByArticleId(comment.getArticleId()));
                    } catch (Exception e) {
                        log.warn("获取文章标签失败，文章ID: {}", comment.getArticleId(), e);
                    }
                }
            });
            
            return commentPage;
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            return new Page<>(page, size);
        }
    }
    
    @Override
    public Comment getCommentWithRelations(Long id) {
        try {
            Comment comment = baseMapper.selectCommentWithRelations(id);
            if (comment != null && comment.getArticleId() != null) {
                comment.setArticleTags(articleTagService.getTagsByArticleId(comment.getArticleId()));
            }
            return comment;
        } catch (Exception e) {
            log.error("获取评论详情失败，ID: {}", id, e);
            return null;
        }
    }
    
    @Override
    public List<Comment> getCommentsByArticleWithRelations(Long articleId) {
        try {
            List<Comment> comments = baseMapper.selectCommentsByArticleWithRelations(articleId);
            // 为每个评论添加文章标签信息
            comments.forEach(comment -> {
                try {
                    comment.setArticleTags(articleTagService.getTagsByArticleId(articleId));
                } catch (Exception e) {
                    log.warn("获取文章标签失败，文章ID: {}", articleId, e);
                }
            });
            return comments;
        } catch (Exception e) {
            log.error("获取文章评论失败，文章ID: {}", articleId, e);
            return List.of();
        }
    }
    
    @Override
    public List<Comment> getCommentsByUserWithRelations(Long userId) {
        try {
            List<Comment> comments = baseMapper.selectCommentsByUserWithRelations(userId);
            // 为每个评论添加文章标签信息
            comments.forEach(comment -> {
                if (comment.getArticleId() != null) {
                    try {
                        comment.setArticleTags(articleTagService.getTagsByArticleId(comment.getArticleId()));
                    } catch (Exception e) {
                        log.warn("获取文章标签失败，文章ID: {}", comment.getArticleId(), e);
                    }
                }
            });
            return comments;
        } catch (Exception e) {
            log.error("获取用户评论失败，用户ID: {}", userId, e);
            return List.of();
        }
    }

    @Override
    public IPage<Comment> getCommentPage(int page, int size, Long userId, Long articleId, Long parentId) {
        // 使用新的关联查询方法
        return getCommentPageWithRelations(page, size, userId, articleId, parentId, null, null);
    }

    @Override
    public List<Comment> getCommentsByArticleId(Long articleId) {
        // 使用新的关联查询方法
        return getCommentsByArticleWithRelations(articleId);
    }

    @Override
    public List<Comment> getCommentsByUserId(Long userId) {
        // 使用新的关联查询方法
        return getCommentsByUserWithRelations(userId);
    }

    @Override
    @Transactional
    public boolean createComment(Comment comment) {
        try {
            // 设置创建时间和默认状态
            comment.setCreateTime(LocalDateTime.now());
            comment.setUpdateTime(LocalDateTime.now());
            
            // 设置默认状态为待审核（管理员创建的评论可以直接通过）
            if (comment.getStatus() == null) {
                comment.setStatus(0); // 默认待审核
            }
            
            // 初始化数值字段
            if (comment.getLikeCount() == null) {
                comment.setLikeCount(0);
            }
            if (comment.getReportCount() == null) {
                comment.setReportCount(0);
            }
            if (comment.getIsTop() == null) {
                comment.setIsTop(false);
            }
            
            boolean success = this.save(comment);
            if (success) {
                log.info("评论创建成功，评论ID: {}, 文章ID: {}, 用户ID: {}, 状态: {}", 
                    comment.getId(), comment.getArticleId(), comment.getUserId(), getStatusText(comment.getStatus()));
            }
            return success;
        } catch (Exception e) {
            log.error("创建评论失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateComment(Comment comment) {
        try {
            // 检查评论是否存在
            Comment existingComment = this.getById(comment.getId());
            if (existingComment == null) {
                log.warn("评论不存在，ID: {}", comment.getId());
                return false;
            }
            
            // 设置更新时间
            comment.setUpdateTime(LocalDateTime.now());
            
            boolean success = this.updateById(comment);
            if (success) {
                log.info("评论更新成功，评论ID: {}", comment.getId());
            }
            return success;
        } catch (Exception e) {
            log.error("更新评论失败，ID: {}", comment.getId(), e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteComment(Long id) {
        try {
            // 先删除子评论
            QueryWrapper<Comment> childWrapper = new QueryWrapper<>();
            childWrapper.eq("parent_id", id);
            long childCount = this.count(childWrapper);
            if (childCount > 0) {
                this.remove(childWrapper);
                log.info("删除了 {} 条子评论", childCount);
            }
            
            // 再删除主评论
            boolean success = this.removeById(id);
            if (success) {
                log.info("评论删除成功，评论ID: {}", id);
            }
            return success;
        } catch (Exception e) {
            log.error("删除评论失败，ID: {}", id, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean batchDeleteComments(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return true;
            }
            
            // 先删除所有子评论
            QueryWrapper<Comment> childWrapper = new QueryWrapper<>();
            childWrapper.in("parent_id", ids);
            long childCount = this.count(childWrapper);
            if (childCount > 0) {
                this.remove(childWrapper);
                log.info("批量删除了 {} 条子评论", childCount);
            }
            
            // 再删除主评论
            boolean success = this.removeByIds(ids);
            if (success) {
                log.info("批量删除评论成功，数量: {}", ids.size());
            }
            return success;
        } catch (Exception e) {
            log.error("批量删除评论失败，IDs: {}", ids, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean auditComment(Long id, Integer status) {
        try {
            // 状态验证
            if (status == null || (status != 0 && status != 1 && status != 2)) {
                log.warn("无效的审核状态: {}", status);
                return false;
            }
            
            Comment comment = new Comment();
            comment.setId(id);
            comment.setStatus(status);
            comment.setUpdateTime(LocalDateTime.now());
            
            // 记录审核时间
            if (status != 0) { // 不是待审核状态
                comment.setAuditTime(LocalDateTime.now());
                // TODO: 获取当前操作用户ID
                // comment.setAuditUserId(getCurrentUserId());
            }
            
            boolean success = this.updateById(comment);
            if (success) {
                String statusText = getStatusText(status);
                log.info("评论审核成功，评论ID: {}, 状态: {}", id, statusText);
            }
            return success;
        } catch (Exception e) {
            log.error("评论审核失败，ID: {}, 状态: {}", id, status, e);
            return false;
        }
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 0: return "待审核";
            case 1: return "已通过";
            case 2: return "已拒绝";
            default: return "未知";
        }
    }
    
    @Override
    @Transactional
    public boolean likeComment(Long id) {
        try {
            Comment comment = this.getById(id);
            if (comment == null) {
                return false;
            }
            
            int currentLikes = comment.getLikeCount() != null ? comment.getLikeCount() : 0;
            comment.setLikeCount(currentLikes + 1);
            comment.setUpdateTime(LocalDateTime.now());
            
            boolean success = this.updateById(comment);
            if (success) {
                log.info("评论点赞成功，评论ID: {}, 点赞数: {}", id, comment.getLikeCount());
            }
            return success;
        } catch (Exception e) {
            log.error("评论点赞失败，ID: {}", id, e);
            return false;
        }
    }
    
    @Override
    public Object getCommentStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 总评论数
            long totalCount = this.count();
            stats.put("totalCount", totalCount);
            
            // 今日评论数
            QueryWrapper<Comment> todayWrapper = new QueryWrapper<>();
            todayWrapper.apply("DATE(create_time) = CURDATE()");
            long todayCount = this.count(todayWrapper);
            stats.put("todayCount", todayCount);
            
            // 本周评论数
            QueryWrapper<Comment> weekWrapper = new QueryWrapper<>();
            weekWrapper.apply("YEARWEEK(create_time) = YEARWEEK(NOW())");
            long weekCount = this.count(weekWrapper);
            stats.put("weekCount", weekCount);
            
            // 本月评论数
            QueryWrapper<Comment> monthWrapper = new QueryWrapper<>();
            monthWrapper.apply("DATE_FORMAT(create_time, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m')");
            long monthCount = this.count(monthWrapper);
            stats.put("monthCount", monthCount);
            
            // 待审核评论数
            QueryWrapper<Comment> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("status", 0);
            long pendingCount = this.count(pendingWrapper);
            stats.put("pendingCount", pendingCount);
            
            // 已通过评论数
            QueryWrapper<Comment> approvedWrapper = new QueryWrapper<>();
            approvedWrapper.eq("status", 1);
            long approvedCount = this.count(approvedWrapper);
            stats.put("approvedCount", approvedCount);
            
            // 已拒绝评论数
            QueryWrapper<Comment> rejectedWrapper = new QueryWrapper<>();
            rejectedWrapper.eq("status", 2);
            long rejectedCount = this.count(rejectedWrapper);
            stats.put("rejectedCount", rejectedCount);
            
            // 置顶评论数
            QueryWrapper<Comment> topWrapper = new QueryWrapper<>();
            topWrapper.eq("is_top", true);
            long topCount = this.count(topWrapper);
            stats.put("topCount", topCount);
            
            return stats;
        } catch (Exception e) {
            log.error("获取评论统计失败", e);
            return new HashMap<>();
        }
    }
    
    @Override
    @Transactional
    public boolean toggleCommentTop(Long id, Boolean isTop) {
        try {
            Comment comment = new Comment();
            comment.setId(id);
            comment.setIsTop(isTop);
            comment.setUpdateTime(LocalDateTime.now());
            
            boolean success = this.updateById(comment);
            if (success) {
                String action = isTop ? "置顶" : "取消置顶";
                log.info("评论{}成功，评论ID: {}", action, id);
            }
            return success;
        } catch (Exception e) {
            log.error("评论置顶操作失败，ID: {}", id, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean batchAuditComments(List<Long> ids, Integer status) {
        try {
            if (ids == null || ids.isEmpty()) {
                return true;
            }
            
            // 状态验证
            if (status == null || (status != 0 && status != 1 && status != 2)) {
                log.warn("无效的审核状态: {}", status);
                return false;
            }
            
            LocalDateTime now = LocalDateTime.now();
            int successCount = 0;
            
            for (Long id : ids) {
                try {
                    Comment comment = new Comment();
                    comment.setId(id);
                    comment.setStatus(status);
                    comment.setUpdateTime(now);
                    
                    if (status != 0) {
                        comment.setAuditTime(now);
                    }
                    
                    if (this.updateById(comment)) {
                        successCount++;
                    }
                } catch (Exception e) {
                    log.error("批量审核评论失败，ID: {}", id, e);
                }
            }
            
            String statusText = getStatusText(status);
            log.info("批量审核完成，状态: {}, 成功: {}/{}", statusText, successCount, ids.size());
            
            return successCount > 0;
        } catch (Exception e) {
            log.error("批量审核评论失败", e);
            return false;
        }
    }
    
    @Override
    public List<Comment> getTopComments(Long articleId, Integer limit) {
        try {
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            if (articleId != null) {
                wrapper.eq("article_id", articleId);
            }
            wrapper.eq("is_top", true)
                   .eq("status", 1) // 只显示已通过的评论
                   .orderByDesc("create_time");
            
            if (limit != null && limit > 0) {
                wrapper.last("LIMIT " + limit);
            }
            
            return this.list(wrapper);
        } catch (Exception e) {
            log.error("获取置顶评论失败，文章ID: {}", articleId, e);
            return List.of();
        }
    }
    
    @Override
    @Transactional
    public boolean reportComment(Long commentId, String reason) {
        try {
            // 检查评论是否存在
            Comment comment = this.getById(commentId);
            if (comment == null) {
                log.warn("评论不存在，ID: {}", commentId);
                return false;
            }
            
            // 增加举报次数
            int currentReportCount = comment.getReportCount() != null ? comment.getReportCount() : 0;
            comment.setReportCount(currentReportCount + 1);
            comment.setUpdateTime(LocalDateTime.now());
            
            boolean success = this.updateById(comment);
            if (success) {
                log.info("评论举报成功，评论ID: {}, 举报原因: {}, 举报次数: {}", 
                    commentId, reason, comment.getReportCount());
                
                // 如果举报次数超过阈值，自动设置为待审核状态
                if (comment.getReportCount() >= 3 && comment.getStatus() == 1) {
                    auditComment(commentId, 0); // 设为待审核
                    log.warn("评论因举报过多自动设为待审核状态，ID: {}", commentId);
                }
            }
            return success;
        } catch (Exception e) {
            log.error("举报评论失败，ID: {}", commentId, e);
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getCommentReports(Long commentId) {
        try {
            // 这里简化实现，实际项目中应该有专门的举报表
            Comment comment = this.getById(commentId);
            List<Map<String, Object>> reports = new java.util.ArrayList<>();
            
            if (comment != null && comment.getReportCount() != null && comment.getReportCount() > 0) {
                Map<String, Object> report = new HashMap<>();
                report.put("commentId", commentId);
                report.put("reportCount", comment.getReportCount());
                report.put("status", comment.getStatus());
                report.put("createTime", comment.getCreateTime());
                report.put("updateTime", comment.getUpdateTime());
                reports.add(report);
            }
            
            return reports;
        } catch (Exception e) {
            log.error("获取评论举报记录失败，ID: {}", commentId, e);
            return List.of();
        }
    }
}
